#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFSIZE 1000

int main (int argc, char *argv[])
{

  int s;
  int fd;
  int len;
  int i;

  struct sockaddr_in my_addr;
  struct sockaddr_in remote_addr;

  int sin_size;
  char buf[BUFSIZE];

  if (argc != 2) {
    printf("usage: %s port\n", argv[0]);
    printf("eg: \n");
    printf("%s 8888\n", argv[0]);
    exit(0);
  }
  
  memset (&my_addr, 0, sizeof (my_addr));
  my_addr.sin_family = AF_INET;
  my_addr.sin_addr.s_addr = INADDR_ANY;
  my_addr.sin_port = htons (strtol(argv[1], NULL, 10));
  
  if ((s = socket (PF_INET, SOCK_STREAM, 0)) < 0) {
      perror ("socket");
      return 1;
  }

  if (bind (s, (struct sockaddr *) &my_addr, sizeof (struct sockaddr)) < 0)
  {

      perror ("bind");

      return 1;

    }

  listen (s, 5);

  sin_size = sizeof (struct sockaddr_in);

  if ((fd = accept (s, (struct sockaddr *) &remote_addr, &sin_size)) < 0)

    {

      perror ("accept");

      return 1;

    }

  printf ("accept client %s\n", inet_ntoa (remote_addr.sin_addr));
  
  
//  len = send (fd, "Welcome to my serve\n", 21, 0);
  while ((len = recv (fd, buf, BUFSIZE, 0)) > 0)
  {
      
      printf ("recv[%d]:",len);
      for(i=0;i<len;i++)
      {
      	printf("%c",buf[i]);	
      }
      printf("\n");
      //memset(buf,0x0,sizeof(buf));
     // strcat(buf,"\x60\x00\x03\x00\x07\x30");
      if (buf[0] == 'q') {
        break;
      }     

      printf ("send[%d]:",len);
      for(i=0;i<len;i++)
      {
      	printf("%c",buf[i]);	
      }
      printf("\n");
      
      if (send (fd, buf, len, 0) < 0)
			{
			 //perror ("write");
			 printf("send error!\n");
			 //return 1;
			}
			else
			{
				printf("send successfull!\n");
				}

    }

  close (fd);
  close (s);

  return 0;

}